<?php

namespace app\sys\command;

use think\Db;
use think\console\Command;
use think\console\Input;
use think\console\Output;

// 定时任务 - 财务报表 每天00：01结算
class Finance extends Command
{
    protected function configure()
    {
        $this->setName('finance')->setDescription('财务报表 统计昨天销售情况');
    }

    protected function execute(Input $input, Output $output)
    {
        $output->writeln('================'.date('Y-m-d H:i:s').' Crontab job start================');

        $this->job();

        $output->writeln('================'.date('Y-m-d H:i:s').' Crontab job end================');
    }

    private function job()
    {
        //统计昨天销售情况
        $sell_total = $sell_cost = $red_packet = $refund = $predict = $profit = 0;
        $bt = strtotime(date('Y-m-d')) - 86400;
        $et = strtotime(date('Y-m-d 23:59:59')) - 86400;
        // 预计盈利
        $result = Db::name('order')->where(['ct' => [['gte', $bt], ['lte', $et]], 'status' => ['in', [1, 2, 3, 5, 6, 8, 10]]])->aggregate(['_id' => null, 'total_fee' => ['$sum' => '$total_fee'], 'supply_cost' => ['$sum' => '$supply_cost'], 'gang_supply_cost' => ['$sum' => '$gang_supply_cost']/*, 'total_red_packet' => ['$sum' => '$total_red_packet']*/]);
        // 真实利润 合计交易完成的订单（不能退款的订单）
        $result_profit = Db::name('order')->where(['ct' => [['gte', $bt], ['lte', $et]], 'status' => 10])->aggregate(['_id' => null, 'total_fee' => ['$sum' => '$total_fee'], 'supply_cost' => ['$sum' => '$supply_cost'], 'gang_supply_cost' => ['$sum' => '$gang_supply_cost']]);
        // 退款成功的合计
        $result_refund = Db::name('order')->where(['ct' => [['gte', $bt], ['lte', $et]], 'status' => 11])->aggregate(['_id' => null, 'total_fee' => ['$sum' => '$total_fee']]);
        // 交易完成的合计
        $result_over = Db::name('order')->where(['ct' => [['gte', $bt], ['lte', $et]], 'status' => 10])->aggregate(['_id' => null, 'total_fee' => ['$sum' => '$total_fee']]);

        $sell_total = round($result[0]['total_fee'], 2);
        $sell_cost = round($result[0]['supply_cost'], 2);
        $gang_supply_cost = round($result[0]['gang_supply_cost'], 2);
        $refund = round($result_refund[0]['total_fee'], 2);
        $red_packet = round($sell_total - $gang_supply_cost, 2);
        $predict = round(($gang_supply_cost - $sell_cost) * 0.994, 2);
        $profit = round(($result_profit[0]['gang_supply_cost'] - $result_profit[0]['supply_cost']) * 0.994, 2);
        $row = ['sale' => $sell_total, 'sale_cost' => $sell_cost, 'red_packet' => $red_packet, 'predict' => $predict, 'refund' => $refund, 'profit' => $profit, 'ct' => time()];
        Db::name('finance')->insert($row);
        echo json_encode($row).PHP_EOL;
    }
}
